package cn.com.haopy.yue.ai.wx.service;


import cn.com.haopy.yue.ai.core.config.ChatApiProperties;
import cn.com.haopy.yue.ai.core.executor.ExecutorCore;
import cn.com.haopy.yue.ai.core.executor.ExecutorScheduledCore;
import cn.com.haopy.yue.ai.db.entity.arisk.AIRiskPapers;
import cn.com.haopy.yue.ai.db.entity.arisk.AIRiskPapersIllness;
import cn.com.haopy.yue.ai.db.entity.arisk.AIRiskPapersIndex;
import cn.com.haopy.yue.ai.db.service.hos.*;
import cn.com.haopy.yue.ai.wx.dto.AIChartMsgResponseDto;
import cn.com.haopy.yue.ai.wx.utils.AIChatParseDataUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Ai聊听会话接口
 */
@Service
@Slf4j
public class PaperIllnessToAISyncService {
    @Autowired
    private ChatAiApiService chatAiApiService;

    @Autowired
    private ChatApiProperties chatProperties;

    @Autowired
    AIRiskPapersIllnessService riskPapersIllnessService;

    @Autowired
    AIRiskPapersService riskPapersService;

    @Autowired
    AIRiskCheckIndexService riskCheckIndexService;

    @Autowired
    AIRiskPapersIndexService riskPapersIndexService;

    @Autowired
    WxPaperPdfService wxPaperPdfService;

    @Autowired
    AIRiskIllnessService riskIllnessService;


    /**
     * 疾病风险评估
     *
     * @param illnesses
     */
    @Async
    public void syncChatIllness(Integer paperId, List<AIRiskPapersIllness> illnesses) {
        illnesses.forEach(item -> {
            ExecutorCore.execute(() -> {
                try {
                    AIChartMsgResponseDto msgResponseDto = chatAiApiService.chatMessage(item.getId() + "", "", item.getInputParams(), item.getQuestion(), chatProperties.getRiskKey());
                    item.setIsAnswer(Boolean.TRUE);


                    String answer = msgResponseDto.getAnswer();

                    item.setResult(answer);

                    try {

                        JSONObject json = AIChatParseDataUtil.json2Obj(answer);

                        String currentRiskLevel = json.getJSONObject("riskAssessment").getString("currentRiskLevel").split("，")[0];

                        String currentRiskLevelScore = json.getJSONObject("riskAssessment").getString("currentRiskLevel").split("，")[1].trim();

                        item.setRisk(currentRiskLevel);
                        item.setRiskScore(new BigDecimal(currentRiskLevelScore));
                        item.setResultJson(json);
                    } catch (Exception e) {
                        log.error(e.toString());
                    }


                    riskPapersIllnessService.updateById(item);

                    //创建pdf

                    Integer count = riskPapersIllnessService.getNotAnswerByPapersIdCount(paperId);

                    if (count <= 0) {
                        wxPaperPdfService.createPdfByPaperId(paperId);
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
        });

    }


    /**
     * 疾病风险评估
     *
     * @param illnesses
     */
    @Async
    public void syncChatIllnessNew(Integer paperId, List<AIRiskPapersIllness> illnesses) {
        illnesses.forEach(item -> {
            ExecutorCore.execute(() -> {
                try {
                    AIChartMsgResponseDto msgResponseDto = chatAiApiService.chatMessage(item.getId() + "", "", item.getInputParams(), item.getQuestion(), chatProperties.getRiskKey());
                    item.setIsAnswer(Boolean.TRUE);


                    String answer = msgResponseDto.getAnswer();

                    item.setResult(answer);

                    try {

                        JSONObject json = AIChatParseDataUtil.json2Obj(answer);


                        //json 为空不解析
                        if (Objects.isNull(json)) {
                            return;
                        }


                        String currentRiskLevel = json.getJSONObject("content").getJSONObject("risk_analise").getJSONObject("currentRiskLevel").getString("riskLevel").split("，")[0];

                        String currentRiskLevelScore = json.getJSONObject("content").getJSONObject("risk_analise").getJSONObject("currentRiskLevel").getString("riskLevel").split("，")[1];

                        item.setRisk(currentRiskLevel);
                        item.setRiskScore(new BigDecimal(currentRiskLevelScore));
                        item.setResultJson(json);
                    } catch (Exception e) {
                        log.error(e.toString());
                    }


                    riskPapersIllnessService.updateById(item);

                    //创建pdf

                    Integer count = riskPapersIllnessService.getNotAnswerByPapersIdCount(paperId);

                    if (count <= 0) {
                        wxPaperPdfService.createPdfByPaperId(paperId);
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
        });

    }


    /**
     * 风险评估报告总结
     *
     * @param paperId
     */
    @Async
    public void syncPaperSummary(Integer paperId) {
        ExecutorScheduledCore.getExecutorService().schedule(() -> {
            try {
                AIRiskPapers paper = riskPapersService.getById(paperId);
                if (Objects.isNull(paper)) {
                    return;
                }


                List<AIRiskPapersIndex> papersIndexList = riskPapersIndexService.getNotEmptyByPapersId(paperId);
                String inputParams = "年龄：" + paper.getAge() + " 岁。";
                for (AIRiskPapersIndex paperIndex : papersIndexList) {
                    if (paperIndex.getIndexName().equals("年龄")) {
                        continue;
                    }

                    if (StringUtils.hasText(paperIndex.getIndexValue())) {
                        inputParams += paperIndex.getIndexName() + "：" + paperIndex.getIndexValue() + "。";
                    }
                }

                if (inputParams.length() > AIChatParseDataUtil.AiInputLenghth) {
                    inputParams = inputParams.substring(0, AIChatParseDataUtil.AiInputLenghth);
                }


                List<AIRiskPapersIllness> listIllness = riskPapersIllnessService.getByPapersId(paperId);

                String query = "";
                query = listIllness.stream()
                        .map(obj -> obj != null ? obj.getIllnessName() : "")
                        .collect(Collectors.joining("，"));

                for (int i = 1; i < 5; i++) {
                    syncPaperSummaryType(paper, i + "", query, inputParams);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }


        }, 4, TimeUnit.SECONDS);
    }


    /**
     * @param paper
     * @param type    1、检查建议 2、生活建议 3、饮食建议 4、运动建议
     * @param illness
     * @param query
     */
    @Async
    public void syncPaperSummaryType(AIRiskPapers paper, String type, String illness, String query) {
        ExecutorCore.execute(() -> {
            try {
                //System.out.println("type:" + type);
                //System.out.println(inputParams);

                Map<String, Object> inputParams = new HashMap<>();
                inputParams.put("select", type);
                inputParams.put("input", illness);


                AIChartMsgResponseDto msgResponseDto = chatAiApiService.chatMessage(paper.getUserId() + "", "", inputParams, query, chatProperties.getSummaryKey());


                String answer = msgResponseDto.getAnswer();


                try {

                    JSONObject jsonObject = AIChatParseDataUtil.json2Obj(answer);
                    //json 为空不解析
                    if (Objects.isNull(jsonObject)) {
                        return;
                    }

                    String text = jsonObject.getString("text");
                    System.out.println(text);
                    Gson gson = new Gson();

                    String[] suggest = gson.fromJson(text, String[].class);

                    LambdaUpdateWrapper<AIRiskPapers> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(AIRiskPapers::getId, paper.getId());

                    AIRiskPapers upPaper = new AIRiskPapers();
                    if (type.equals("1")) {
                        //检查
                        upPaper.setCheckSuggest(suggest);
                    } else if (type.equals("2")) {
                        //生活
                        upPaper.setLifeSuggest(suggest);
                    } else if (type.equals("3")) {
                        //饮食
                        upPaper.setFoodsSuggest(suggest);

                    } else {
                        //运动
                        upPaper.setSportsSuggest(suggest);
                    }

                    riskPapersService.update(upPaper, updateWrapper);

                } catch (Exception e) {
                    log.error(e.toString());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        });
    }


}
